import { GetSelfTaskDetailQuery, TaskEntity } from "@/queries/task";
import { useQuery } from "@apollo/client";
import { useCallback, useMemo } from "react";

const useTask = (taskId: number) => {
  const { data, loading, refetch } = useQuery(GetSelfTaskDetailQuery, {
    variables: { id: taskId },
  });
  const entity: TaskEntity = useMemo(() => {
    if (!data) return;
    return data.getSelfTaskDetail;
  }, [data]);

  const taskItems = useMemo(() => {
    return entity?.TaskItem || [];
  }, [entity]);

  const teachers = useMemo(
    () =>
      entity?.TaskOnClasses[0]?.classes?.TeacherOnClasses?.map(
        (e) => e.teacher
      ) || [],
    [entity]
  );

  const userOnTask = useMemo(() => entity?.UserOnTask || [], [entity]);

  const getTeacherDetail = useCallback(
    (teacherid: number) => {
      const teacherItem =
        userOnTask.find((e) => e.teacher.id === teacherid)?.items || [];
      const teacherCommon =
        userOnTask.find((e) => e.teacher.id === teacherid)?.common || "";
      return { teacherItem, teacherCommon };
    },
    [userOnTask]
  );
  return {
    entity,
    getTeacherDetail,
    taskItems,
    teachers,
    userOnTask,
    loading,
    refetch,
  };
};
export default useTask;
